package fox.framework.rpc.endpoint.netty.heartbeat;

import fox.framework.rpc.client.heartbeat.Ping;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author cuichao
 * @Description: RpcHeartbeatHandler
 * @Date: create in 2021/2/10 22:18
 */
public class RpcHeartbeatHandler extends SimpleChannelInboundHandler<Ping> {

    private NettyHeartbeat heartbeat;

    public RpcHeartbeatHandler(NettyHeartbeat heartbeat) {
        this.heartbeat = heartbeat;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        heartbeat.registry(ctx.channel());
        super.channelActive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Ping ping) throws Exception {
        System.out.println(ping.get());
        if( Ping.PING.equals(ping.get())){
            heartbeat.pong();
        }
        if(Ping.PONG.equals(ping.get())){
            heartbeat.touch();
        }
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(!(evt instanceof IdleStateEvent)){
            super.userEventTriggered(ctx,evt);
        }
        heartbeat.trigger(((IdleStateEvent) evt));

    }


}
